const db = require('../config/db')
const util = require('../util/index')
const productModel = '../schema/product'
const categoryDetail = '../schema/category_detail'
const categoryModel = '../schema/category'
const Mall = db.MallSequelize   //引入数据库
const product = Mall.import(productModel)  //实例化product 
const category_detail = Mall.import(categoryDetail)
const category = Mall.import(categoryModel)
category.hasMany(category_detail)
category_detail.belongsTo(category)
category_detail.hasMany(product)
product.belongsTo(category_detail)
// 获取全部商品
const getProducts = async (query) => {
  let page = Number(query.page)
  let limit = Number(query.limit)
  const result = await product.findAndCountAll({
    include: [category_detail],
    offset: parseInt(page*10)*parseInt(limit/10),
    limit: limit,
    order: [['created_at', 'desc']]
  })
  return result
}
// 获取上架商品
const getStatusProducts = async (query) => {
  const result = await product.findAll({
    include: [category_detail],
    where: {
      status: 1
    },
    offset: Number(query.page*10),
    limit: Number(query.limit)
  })
  return result
}
// 获取热门商品
const getHotProducts = async () => {
  const result = await product.findAll(
    {
      where: {
        hot: 1,
        status: 1
      }
    },
    { include: [category_detail] }
  )
  return result
}
// 添加商品
const addProduct = async (data) => {
  if(data.hot) {
    data.hot = 1
  }else {
    data.hot = 0
  }
  await product.create({
    name: data.name,
    price: data.price,
    address: data.address,
    inventory: data.inventory,
    remark: data.remark,
    status: 1,
    hot: data.hot,
    category_detail_id: data.category_detail_id,
    image_url: data.image_url,
    image_detail_url: data.image_detail_url,
    content: data.content
  })
  return true
}
// 根据搜索关键字获取商品
const getProductsByKeyWords = async (keywords) => {
  if(keywords.id) {
    const result = await product.findAll(
      { 
        include: [category_detail],
        where: {
          id: Number(keywords.id)
        } 
      },
    )
    return result
  }else if(keywords.name) {
    const result = await product.findAll(
      { 
        include: [category_detail],
        where: {
          name: {
            $like: `%${keywords.name}%`
          }
        } 
      },
    )
    return result
  }
}
// 根据id获取商品
const getProductById = async (id) => {
  const result = await product.findOne({
    where: {
      id: Number(id)
    }
  })
  return result
}
// 根据id修改商品
const updateProduct = async (id, data) => {
  if(data.hot) {
    data.hot = 1
  }else {
    data.hot = 0
  }
  await product.update(
    {
      name: data.name,
      price: data.price,
      category: data.category,
      address: data.address,
      inventory: data.inventory,
      remark: data.remark,
      hot: data.hot,
      category_detail_id: data.category_detail_id,
      image_url: data.image_url,
      image_detail_url: data.image_detail_url,
      content: data.content
    },
    {
      where: {
        id: id
      }
    }
  )
  return true
}
// 根据商品类别查找商品
const getProductsByCategory = async (typeid) =>{
  const result = await product.findAll(
    {
      include: [category_detail],
      where: {
        category_detail_id: typeid,
        $and: {
          status: 1
        }
      }
    }
  )
  return result
}
// 根据id修改商品状态
const updateStatus = async (id, data) => {
  await product.update(
    {
      status: data.status
    },
    {
      where: {
        id: id
      }
    }
  )
  return true
}
// 根据id修改商品库存
const updateInventory = async (id, data) => {
  await product.update(
    {
      inventory: data.inventory,
      sale_count: data.sale_count
    },
    {
      where: {
        id: id
      }
    }
  )
  return true
}
// 获取某类商品销售量
const getSaleByCategory = async (id) => {
  const result = await product.findAll(
    {
      where: {
        category_detail_id: Number(id)
      }
    }
  )
  return result
}
// 获取最新商品
const getNewProducts = async () => {
  let prevTime = util.formatTime(new Date())
  let nextTime = util.formatTime2(new Date())
  const result = await product.findAll(
    {
      where: {
        created_at: {
          $between: [prevTime, nextTime]
        }
      }
    }
  )
  return result
}
// 根据筛选条件排序
const getProductsByFilter = async (query) => {
  if(query.column == 'high_price') {
    if(query.typeid) {
      const result = await product.findAll(
        {
          include: [category_detail],
          where: {
            category_detail_id: query.typeid
          },
          order: [['price', 'desc']]
        }
      )
      return result
    }else if(query.name) {
      const result = await product.findAll(
        {
          include: [category_detail],
          where: {
            name: {
              $like: `%${query.name}%`
            }
          },
          order: [['price', 'desc']]
        }
      )
      return result
    }
  }
  
  if(query.column == 'lower_price') {
    if(query.typeid) {
      const result = await product.findAll(
        {
          include: [category_detail],
          where: {
            category_detail_id: query.typeid
          },
          order: [['price', 'asc']]
        }
      )
      return result
    }else if(query.name) {
      const result = await product.findAll(
        {
          include: [category_detail],
          where: {
            name: {
              $like: `%${query.name}%`
            }
          },
          order: [['price', 'asc']]
        }
      )
      return result
    }
  }

  if(query.column == 'high_sale') {
    if(query.typeid) {
      const result = await product.findAll(
        {
          include: [category_detail],
          where: {
            category_detail_id: query.typeid
          },
          order: [['sale_count', 'desc']]
        }
      )
      return result
    }else if(query.name) {
      const result = await product.findAll(
        {
          include: [category_detail],
          where: {
            name: {
              $like: `%${query.name}%`
            }
          },
          order: [['sale_count', 'desc']]
        }
      )
      return result
    }
  }

  if(query.column == 'lower_sale') {
    if(query.typeid) {
      const result = await product.findAll(
        {
          include: [category_detail],
          where: {
            category_detail_id: query.typeid
          },
          order: [['sale_count', 'asc']]
        }
      )
      return result
    }else if(query.name) {
      const result = await product.findAll(
        {
          include: [category_detail],
          where: {
            name: {
              $like: `%${query.name}%`
            }
          },
          order: [['sale_count', 'asc']]
        }
      )
      return result
    }
  }
}
module.exports = {
  getProducts,
  getStatusProducts,
  addProduct,
  getProductById,
  getProductsByKeyWords,
  updateProduct,
  updateStatus,
  getProductsByCategory,
  getHotProducts,
  updateInventory,
  getSaleByCategory,
  getNewProducts,
  getProductsByFilter
}